
//
// Copyright 2009 Arne Halvorsen (arne.halvorsen@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Project page: http://code.google.com/p/mf4j/

//
// 091116 - aha42 - Starts in line change tracking.
// 091121 - aha42 - Added project page link (google code) to header comment.
// 091210 - aha42 - IOException -> FlickrException.
//

package org.aha.mf4j.reflection;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

import org.aha.mf4j.FlickrException;
import org.aha.mf4j.response.FlickrObject;

/**
 * <p>
 *   Represents a Flickr response error.
 * </p>
 * @author Arne Halvorsen (aha42)
 */
public final class FlickrError 
{
  private final String m_code;
  
  private final String m_message;
  
  private final String m_explanation;
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param errorFo {@link FlickrObject} of type {@code error} to construct 
   *                from.
   * @throws FlickrException If fails.
   */
  public FlickrError(FlickrObject errorFo) throws FlickrException
  {
    if (errorFo==null)
    {
      throw new NullPointerException("errorFo");
    }
    
    errorFo.assertType("error");  
    
    m_code=errorFo.getMandatoryAttribute("code");
    m_message=errorFo.getAttribute("message");
    m_explanation=errorFo.getValue();
  }
  
  /**
   * <p>
   *   Gets error code.
   * </p>
   * @return Code.
   */
  public String getErrorCode(){ return m_code; }
  
  /**
   * <p>
   *   Gets error message.
   * </p>
   * @return Message or {@code null} if has none.
   */
  public String getMessage(){ return m_message; }
  
  /**
   * <p>
   *   Gets error explanation (what is found in cdata).
   * </p>
   * @return Explanation or {@code null} if has none.
   */
  public String getExplanation(){ return m_explanation; }
  
  @Override
  public String toString() 
  {
    CharArrayWriter caw=new CharArrayWriter();
    PrintWriter pw=new PrintWriter(caw);
    
    pw.print("Error "+m_code);
    if (m_message!=null) pw.print(" : "+m_message);
    pw.println();
    if (m_explanation!=null)
    {
      pw.println();
      pw.println(m_explanation);
    }
    
    pw.flush();
    return caw.toString();
  }
  
  /**
   * <p>
   *   The empty array shared.
   * </p>
   */
  public static final FlickrError[] E_ARRAY=new FlickrError[0];
  
}
